<template>
  <div class="exam-page flex-col">
    <div class="exam-selected-section flex-col">
      <div class="exam-option-group flex-row justify-between">
        <div
          class="exam-option"
          v-for="option in options"
          :key="option.value"
          @click="selectOption(option.value)"
          :class="{ selected: selectedOption === option.value }"
        >
          {{ option.label }}
        </div>
      </div>
      <div class="center-box">
        <span class="exam-list-title">推荐竞赛</span>
        <el-form
          :inline="true"
          class="exam-navigation flex-row justify-between"
        >
          <el-form-item
            label="竞赛时间"
            prop="datetimerange"
            class="exam-navigation-box"
          >
            <el-date-picker
              style="width: 360px"
              v-model="datetimeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button @click="onSearch" plain type="primary">
              搜索
            </el-button>
            <el-button @click="onReset" plain type="info">
              重置
            </el-button>
          </el-form-item>
        </el-form>
        <!-- </div> -->
        <div class="exam-list-group flex-row">
          <div
            class="exam-list-item flex-col"
            v-for="(exam, index) in examList"
            :key="index"
          >
            <div>
              <img src="@/assets/images/exam.png" />
            </div>
            <div class="right-info">
              <span class="exam-title">{{ exam.title }}</span>
              <div class="exam-content flex-col justify-between">
                <span>开赛时间：{{ exam.startTime }}</span>
                <span>结束时间：{{ exam.endTime }}</span>
              </div>
              <div class="exam-button-container">
                <span
                  class="exam-hash-entry"
                  v-if="isOngoingAndUnregisteredCompetition(exam)"
                >
                  已开赛
                </span>
                <span
                  class="exam-hash-entry"
                  v-if="isEntryAndNotStart(exam)"
                >
                  已报名
                </span>
                <div v-if="isHistoryExam(exam)">
                  <el-button
                    class="exam-practice-button"
                    type="primary"
                    plain
                    @click="goExam(exam)"
                  >
                    竞赛练习
                  </el-button>
                  <el-button
                    class="exam-rank-button"
                    type="primary"
                    plain
                    @click="togglePopover(exam.examId)"
                  >
                    查看排名
                  </el-button>
                </div>
                <el-button
                  class="exam-start-button"
                  type="primary"
                  plain
                  v-if="isStartExam(exam)"
                  @click="goExam(exam)"
                >
                  开始答题
                </el-button>
                <el-button
                  class="exam-enter-button"
                  type="primary"
                  plain
                  v-if="isCanEntry(exam)"
                  @click="enterExam(exam.examId)"
                >
                  报名参赛
                </el-button>
              </div>
            </div>
          </div>
        </div>
        <div class="exam-page-pagination flex-row">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            v-model:current-page="params.pageNo"
            v-model:page-size="params.pageSize"
            :page-sizes="[3, 6, 9, 12]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>

  <el-dialog
    v-model="dialogVisible"
    width="600px"
    top="30vh"
    :show-close="true"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    class="oj-login-dialog-centor"
    center
  >
    <el-table :data="examRankList">
      <el-table-column label="排名" prop="examRank" />
      <el-table-column label="用户昵称" prop="nickName" />
      <el-table-column label="用户得分" prop="score" />
    </el-table>
    <el-pagination
      class="range_page"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="rankTotal"
      v-model:current-page="rankParams.pageNo"
      v-model:page-size="rankParams.pageSize"
      :page-sizes="[5, 10, 15, 20]"
      @size-change="handleRankSizeChange"
      @current-change="handleRankCurrentChange"
    />
  </el-dialog>
</template>

<script setup>
  import { reactive, ref } from 'vue'
  import {
    getExamListService,
    enterExamService,
    getExamRankListService
  } from '@/api/exam'
  import { getUserInfoService } from '@/api/user'
  import router from '@/router'
  import { useUserStore } from '@/stores'
  const userStore = useUserStore()

  // 题目列表
  const examList = ref([])
  // 竞赛总数
  const total = ref(0)
  // 初始化选中的文本(竞赛列表选项，被选中的样式是蓝色)
  const selectedOption = ref(0)
  // 竞赛列表选项
  const options = ref([
    { label: '未完赛', value: 0 },
    { label: '历史竞赛', value: 1 }
  ])
  // 日期时间范围响应式数据
  const datetimeRange = ref([])
  // 分页参数和竞赛列表类型
  const params = reactive({
    pageNo: 1,
    pageSize: 9,
    startTime: '',
    endTime: '',
    type: 0
  })
  //日期时间格式化
  function formatDateTime(date) {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }
  // 获取竞赛列表
  async function getExamList() {
    // 获取开始时间
    if (datetimeRange.value[0] instanceof Date) {
      params.startTime = formatDateTime(datetimeRange.value[0])
    }
    // 获取结束时间
    if (datetimeRange.value[1] instanceof Date) {
      params.endTime = formatDateTime(datetimeRange.value[1])
    }
    const result = await getExamListService(params)
    examList.value = result.list
    total.value = result.totals
  }
  getExamList()
  // 竞赛列表类型选项
  async function selectOption(type) {
    selectedOption.value = type
    params.pageNo = 1
    params.type = type
    getExamList()
  }

  // 搜索
  function onSearch() {
    params.pageNo = 1
    getExamList()
  }
  // 重置
  function onReset() {
    params.startTime = params.endTime = ''
    datetimeRange.value.length = 0
    params.pageNo = 1
    params.pageSize = 9
    params.type = 0
    getExamList()
  }

  // 分页大小改变
  function handleSizeChange(newSize) {
    params.pageNo = 1
    getExamList()
  }
  // 当前页改变
  function handleCurrentChange(newPage) {
    getExamList()
  }
  // 根据竞赛开始时间和当前时间判断竞赛是否已开赛
  function isOngoingAndUnregisteredCompetition(exam) {
    const now = new Date() //当前时间
    return (
      new Date(exam.startTime) < now &&
      new Date(exam.endTime) > now &&
      !exam.enter
    )
  }
  // 根据竞赛开始时间和当前时间以及竞赛的enter判断竞赛是否已经报名
  function isEntryAndNotStart(exam) {
    const now = new Date()
    return new Date(exam.startTime) > now && exam.enter
  }
  // 根据竞赛结束时间和当前时间判断竞赛是否是历史竞赛
  function isHistoryExam(exam) {
    const now = new Date()
    return new Date(exam.endTime) < now
  }
  // 已开赛的竞赛并且已经报名就允许答题
  function isStartExam(exam) {
    const now = new Date()
    return (
      new Date(exam.startTime) < now &&
      new Date(exam.endTime) > now &&
      exam.enter
    )
  }
  // 还未报名且还未开赛的竞赛允许报名
  function isCanEntry(exam) {
    const now = new Date()
    return new Date(exam.startTime) > now && !exam.enter
  }
  // 检查登录状态
  const isLogin = ref(false)
  async function checkLogin() {
    if (userStore.token) {
      await getUserInfoService()
      isLogin.value = true
    }
  }
  // 报名竞赛
  async function enterExam(examId) {
    await checkLogin()
    if (!isLogin.value) {
      ElMessage.error('请先登录后报名参赛,谢谢')
      return
    }
    const enterExamDTO = ref({
      examId: examId
    })
    await enterExamService(enterExamDTO.value)
    ElMessage.success('您已报名成功，请按时参赛')
    getExamList() //报名成功后刷新竞赛列表
  }
  // 进入竞赛
  function goExam(exam) {
    //需要后端提供一个获取竞赛中第一道题目的id接口
    router.push(
      `/c-oj/anwser?examId=${exam.examId}&examTitle=${exam.title}&examEndTime=${exam.endTime}`
    )
  }
  // 竞赛排名响应式对象
  const rankParams = reactive({
    examId: '',
    pageNo: 1,
    pageSize: 9
  })
  const examRankList = ref([])
  const rankTotal = ref(0)

  // 根据分页大小获取竞赛列表
  function handleRankSizeChange(newSize) {
    rankParams.pageNo = 1
    getExamRankList()
  }
  // 根据当前页获取竞赛列表
  function handleRankCurrentChange(newPage) {
    getExamRankList()
  }
  // 排名列表显示响应式数据
  const dialogVisible = ref(false)
  // 获取竞赛排名列表
  async function getExamRankList() {
    const result = await getExamRankListService(rankParams)
    examRankList.value = result.list
    rankTotal.value = result.totals
  }
  // 点击查看排名触发getExamRankList函数
  function togglePopover(examId) {
    dialogVisible.value = true
    rankParams.examId = examId
    getExamRankList()
  }
</script>

<style lang="scss" scoped>
  .exam-page {
    background-color: rgba(247, 247, 247, 1);
    position: relative;
    overflow: hidden;
    display: flex;

    .center-box {
      max-width: 1520px;
      margin: 0 auto;
      width: 100%;
      min-height: 368px;
      background: #ffffff;
      border-radius: 16px;
      padding: 0 20px;
      padding-top: 30px;
      margin-top: 10px;
    }

    .exam-selected-section {
      margin: 0 auto;
      margin-bottom: 20px;
      position: relative;
      padding-top: 50px;
      max-width: 1520px;
      width: 100%;

      .exam-option-group {
        width: fit-content;
        height: 50px;
        position: absolute;
        top: 0;
        left: 0;

        .exam-option {
          cursor: pointer;
          padding: 10px;
          border-bottom: 2px solid transparent;
          transition: all 0.3s ease;
          font-family: PingFangSC, PingFang SC;
          font-weight: 600;
          font-size: 18px;
          color: #222;
          height: 50px;
          width: fit-content;
          display: flex;
          justify-content: center;
          align-items: center;
          margin-right: 20px;
        }

        .exam-option.selected {
          color: #32c5ff;
          border-bottom: 2px solid #32c5ff;
        }
      }

      .exam-list-title {
        height: 24px;
        font-family: PingFangSC, PingFang SC;
        font-weight: 600;
        font-size: 18px;
        color: #222222;
        line-height: 25px;
        text-align: left;
        margin-bottom: 30px;
        display: block;
      }

      :deep(.exam-navigation) {
        width: 554px;
        height: 40px;
        font-size: 100px;
        margin-bottom: 30px;

        .el-form-item {
          margin-right: 20px;
        }

        .el-form-item__label {
          background: #fff;
        }

        .exam-navigation-box {
          background-color: rgba(242, 243, 244, 1);
          border-radius: 6px;
          height: 30px;
          // width: 460px;
          font-weight: 700;
        }
      }

      .exam-list-group {
        // width: 1200px;
        flex-wrap: wrap;

        @media screen and (min-width: 1420px) {
          .exam-list-item {
            width: 32%;

            &:nth-of-type(3n) {
              margin-right: 0;
            }
          }
        }

        @media screen and (max-width: 1419px) {
          .exam-list-item {
            width: 48%;
            margin-right: 2%;

            &:nth-of-type(2n) {
              margin-right: 0;
            }
          }
        }

        @media screen and (max-width: 970px) {
          .exam-list-item {
            width: 100%;
            margin-right: 0;
          }
        }

        .exam-list-item {
          height: 220px;
          background: #f9f9f9;
          border-radius: 10px;
          margin-right: 2%;
          margin-bottom: 20px;
          padding: 20px;
          box-sizing: border-box;
          display: flex;
          align-items: center;
          flex-direction: row;
          justify-content: space-between;
          cursor: pointer;

          .right-info {
            width: calc(100% - 146px);
          }

          .exam-title {
            height: 26px;
            font-family: PingFangSC, PingFang SC;
            font-weight: 600;
            font-size: 18px;
            color: #222222;
            line-height: 26px;
            text-align: left;
            max-width: 90%;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            margin-bottom: 16px;
            display: block;
          }

          .exam-content {
            margin-bottom: 26px;

            span {
              height: 22px;
              font-family: PingFangSC, PingFang SC;
              font-weight: 400;
              font-size: 16px;
              color: #666666;
              line-height: 22px;
              display: block;
              margin-bottom: 12px;
            }
          }

          img {
            width: 126px;
            height: 180px;
            border-radius: 6px;
          }

          &:hover {
            background: #fff;
            box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.1);

            .exam-title {
              color: #32c5ff;
            }

            .el-button {
              background: #f7f7f7;
            }
          }

          .exam-hash-entry {
            float: right;
            font-size: 18px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #999;
          }

          .exam-button-container {
            display: flex;
            justify-content: space-between;
            /* 或者使用 flex-start 来紧密排列按钮 */
            align-items: center;

            /* 如果需要垂直居中 */
            /* 其他样式，如外边距、内边距等 */
            .el-button {
              width: 120px;
              height: 44px;
              background: #f7f7f7;
              border-radius: 4px;
              border: 1px solid #32c5ff;
              font-family: PingFangSC, PingFang SC;
              font-weight: 400;
              font-size: 18px;
              color: #32c5ff;
              line-height: 44px;
              text-align: center;
            }
          }
        }
      }

      .exam-page-pagination {
        width: 594px;
        height: 40px;
        margin: 30px 0 73px 800px;
      }
    }
  }
</style>
